package com.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.annotation.DataSource;
import com.baomidou.mybatisplus.plugins.Page;
import com.entity.SysUser;
import com.enums.DataSourceEnum;
import com.mapper.SysUserMapper;
import com.service.SysUserService;
import com.utils.CaptchaCodeManagerUtils;
import com.utils.Public;
import com.utils.R;
import com.utils.RSA;
import com.utils.SmsUtil;


/**
* 
*
* @author Zyuan
* @version 创建时间：2019年6月22日 下午8:16:59
*/
@RestController
@RequestMapping(value = "/api/user", produces = { "application/json;charset=UTF-8" })
public class UserController {

	@Autowired
	private SysUserService userService;
	@Autowired
	private SysUserMapper userMapper;
    /** 阿里云短信平台参数：access-KeyId */
    @Value("${spring.sms.id}")
    private String accessKeyId;
    
    /** 阿里云短信平台参数：access-secret */
    @Value("${spring.sms.secret}")
    private String accessSecret;
    
    /** 阿里云短信平台参数：template-code */
    @Value("${spring.sms.code}")
    private String templateCode ;
    
    /** 阿里云短信平台参数：sign-name */
    @Value("${spring.sms.name}")
    private String signName;
    
    
    @GetMapping ("/test")
    public R test() {
    	return R.ok("成功");
    }
    
	/**
	 * 小程序登陆
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public R login(@RequestBody Map<String, Object> params) throws Exception{
          if(Public.mapTo(params.get("loginId"), "").length() <= 0){
        	  return R.error("请输入登陆名");
          }
          if(Public.mapTo(params.get("password"), "").length() <= 0){
        	  return R.error("请输入密码");
          }
          return userService.login(params);
	}
	

	/**
	 * 修改密码
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/update/password", method = RequestMethod.POST)
	public R updatePassword(@RequestBody Map<String, Object> params) throws Exception{
		if(StringUtils.isBlank(Public.mapTo(params.get("phone"), ""))){
			return R.error("缺少参数");
		}
		if(StringUtils.isBlank(Public.mapTo(params.get("password"), ""))){
			return R.error("缺少参数");
		}
		String cachedCaptcha = CaptchaCodeManagerUtils.getCachedCaptcha(Public.mapTo(params.get("phone"), ""));
		if (StringUtils.isBlank(cachedCaptcha)) {
			return R.error("请先发送验证码");
		}
		if (!cachedCaptcha.equals(Public.mapTo(params.get("code"), ""))) {
			return R.error("验证码错误");
		}
       return userService.updatePassword(params);
	}
	
	
	/**
	 * 修改用户信息
	 * @param params
	 * @return
	 */
	@DataSource(DataSourceEnum.DB2)
	@RequestMapping(value = "update", method = { RequestMethod.POST })
	public R update(@RequestBody Map<String, Object> params) {
		if(Public.mapTo(params.get("userId"), "").length() <= 0){
			return R.noLogin();
		}
		SysUser userView = new SysUser();
		userView.setId(Public.mapTo(params.get("userId"), ""));
		userView.setName(Public.mapTo(params.get("name"), ""));
		userView.setMobile(Public.mapTo(params.get("mobile"), ""));
		userView.setEmail(Public.mapTo(params.get("email"), ""));
		userView.setSysAreaId(Public.mapTo(params.get("areaId"), ""));
		Boolean suc = userService.updateById(userView);;
		if(!suc){
			return R.error("修改失败");
		}
		return R.ok();
	}
	
	/**
	 * 获取我的资料
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "info", method = { RequestMethod.GET })
	public R info(@RequestParam Map<String, Object> params) {
		if(Public.mapTo(params.get("userId"), "").length() <= 0){
			return R.noLogin();
		}
		if(StringUtils.isBlank(Public.mapTo(params.get("userId"), ""))){
			return R.error("缺少参数");
		}
		Map<String, Object> data = userService.getUserInfo(params);
		if(data == null){
			return R.error("用户不存在");
		}
		Map<String, Object> areaParam = new HashMap<String, Object>();
		areaParam.put("orgId", Public.mapTo(data.get("SYS_AREA_ID"), ""));
		List<Map<String, Object>> managerViewList = userService.getAreaManagerViewList(areaParam);
		
		data.put("areaManager", managerViewList.size() > 0 ? managerViewList.get(0) : new HashMap<>());
		return R.success(data);
	}
	
	
	/**
	 * 获取维护人员列表
	 * @param params
	 * 「
	 *   "areaId":"区域id"
	 * 」
	 * @return 
	 */
	@RequestMapping(value = "/maintain/list", method = RequestMethod.GET)
	public R getMaintainList(@RequestParam Map<String, Object> params){
		Page<Map<String, Object>> pageInfo= userService.getMaintainList(params);
		Map<String, Object> dataList = new HashMap<String, Object>(5);
		dataList.put("list", pageInfo.getRecords());
		dataList.put("totalCount", pageInfo.getTotal());
		
		Map<String, Object> areaParam = new HashMap<String, Object>();
		areaParam.put("orgId", Public.mapTo(params.get("areaId"), ""));
		List<Map<String, Object>> managerViewList = userService.getAreaManagerViewList(areaParam);
		
		dataList.put("areaManager", managerViewList.size() > 0 ? managerViewList.get(0) : new HashMap<>());
		return R.success(dataList);
	}
	
	@ResponseBody
	@RequestMapping(value = "private/rsa", method = { RequestMethod.POST })
	public R getPrivate(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		
		Map<String, Object> keyMap = RSA.initKey();  
		String publicKey = RSA.getPublicKey(keyMap);  
		String privateKey = RSA.getPrivateKey(keyMap);
		
		System.out.println("publicKey : " + publicKey);
		System.out.println("privateKey : " + privateKey);
		String modulus = RSA.getRSAPublicKeyModulusToHex(publicKey);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("publicKey", modulus);
		params.put("privateKey", privateKey);
		return R.success(params);
	}
	
	@DataSource(DataSourceEnum.DB2)
	@RequestMapping(value = "/send/code", method = { RequestMethod.GET })
	public R sendCode(String phone) throws IOException{
		Map<String, Object> searchParam = new HashMap<String, Object>();
		searchParam.put("phone", Public.mapTo(phone, ""));
		Map<String, Object> data =  userMapper.getUserInfo(searchParam);
        if(data == null){
        	return R.error("账号不存在");
        }
//        SmsUtil.sendMessage(phone);
        return R.ok();
	}
	
	
}
